package com.shenyong.shrio;

import com.shenyong.entity.LoginUsers;
import com.shenyong.entity.Users;
import com.shenyong.ladmin.result.ResponseData;
import com.shenyong.service.UserService;
import com.shenyong.util.JwtToken;
import com.shenyong.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 *  自定义的类
 */
@Slf4j
public class UserRealm extends AuthorizingRealm {
    ResponseData responseData = new ResponseData();
    @Autowired
    private UserService userService;


    /**
     * 必须重写此方法，不然Shiro会报错
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 执行授权逻辑
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行授权逻辑");
        String username = JwtUtil.getUsername(principals.toString());
        SimpleAuthorizationInfo info = null;
        Subject subject = SecurityUtils.getSubject();
        Users user = (Users) subject.getPrincipal();
        /**
         * 得到身份对象
         * 查询该用户的权限信息
         */
       // List<String> rolePre = userService.selectRoleDetails(user.getUser_id());
        /**
         * 创建一个Set,来放置用户拥有的权限
         * 创建 SimpleAuthorizationInfo, 并将办好权限列表的Set放入.
         */
        try {
           /* Set<String> roleSet = new HashSet<>();
            for (String role : rolePre) {
                roleSet.add(role);
            }
            info = new SimpleAuthorizationInfo();
            info.setStringPermissions(roleSet);*/
        }catch (Exception e) {
            throw new AuthenticationException("授权失败");
        }

        return info;
    }

    /**
     * 执行认证逻辑
     * @param token
     * @return
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行认证逻辑");
        String autoken = (String) token.getCredentials();
        // 解密获得username，用于和数据库进行对比
        String username = null;
        //这里工具类没有处理空指针等异常这里处理一下(这里处理科学一些)
        username = JwtUtil.getUsername(autoken);
        LoginUsers user = userService.getName(username);
        if (username == null || !JwtUtil.verify(autoken, username,user.getUser().getUser_password())) {
            throw new IncorrectCredentialsException("token认证失败！");
        }
        return new SimpleAuthenticationInfo(user,autoken,getName());
    }
}
